//
//  YZLHomePageCell.m
//  Car
//
//  Created by dllo on 15/10/30.
//  Copyright © 2015年 岳明. All rights reserved.
//

#pragma mark - *每个标签对应的tableView*
#import "YZLHomePageCell.h"
#import "YZLHomePageModel.h"
#import "YZLFocusListModel.h"
#import "YZLFocusImgs.h"
#import "YZLNewsListModel.h"
#import "YZLNewsListCell.h"
#import "YZLNewsScrollCell.h"
#import "Macro.h"
#import "HTTPTOOL.h"
#import "MJRefresh.h"


@interface YZLHomePageCell ()<UITableViewDataSource, UITableViewDelegate, YZLNewsScrollCellDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *modelArray; /**< 装主 Model 的数组 */
@property (nonatomic, strong) NSMutableArray *newsArray; /**< 装新闻 Model 的数组 */

@property (nonatomic, assign) NSInteger nextInteger; /**< 上拉加载参数 */
@property (nonatomic, assign) BOOL isUpLoading; /**< 判断上拉（YES）还是下拉（NO） */
@property (nonatomic, strong) NSString *urlString; /**< 端口 */

@end

@implementation YZLHomePageCell

#pragma mark - 数据解析
- (void)handleDataWithList:(NSInteger )nextInteger {

    // 拼接上端口的参数
    self.urlString = [NSString stringWithFormat:@"http://%@.xcar.com.cn/interface/%@.php?type=%@&cityId=&offset=%ld&limit=10&ver=6.2.2", [self.urlDic objectForKey:@"frist"], [self.urlDic objectForKey:@"last"], [self.urlDic objectForKey:@"type"], nextInteger];
    [HTTPTOOL GETWithURL:self.urlString body:nil httpHead:nil responseStyle:JSON success:^(id result) {

        //如果下拉，则清空数组
        if (self.isUpLoading == NO) {
            [self.modelArray removeAllObjects];
            [self.newsArray removeAllObjects];
        }
        // 解析主 Model
        YZLHomePageModel *hpModel = [YZLHomePageModel yzlHomePageModelWithDic:result];
        NSDictionary *flDic = [result objectForKey:@"focusList"];
        // 解析轮播图 Model
        YZLFocusListModel *flModel = [YZLFocusListModel yzlFocusListModelWithDic:flDic];
        NSDictionary *hfDic = [NSDictionary dictionaryWithObject:flModel forKey:@"focusList"];
        // 解析轮播图图片 Model
        NSArray *fiArr = [flDic objectForKey:@"focusImgs"];
        NSMutableArray *mFiArr = [NSMutableArray array];
        for (NSDictionary *dic in fiArr) {
            YZLFocusImgs *fiModel = [YZLFocusImgs yzlFocusImgsWithDic:dic];
            [mFiArr addObject:fiModel];
        }
        flModel.focusImgs = mFiArr;
        hpModel.focusList = hfDic;
        // 解析新闻 Model
        NSArray *nlArr = [result objectForKey:@"newsList"];
        for (NSDictionary *dic in nlArr) {
            YZLNewsListModel *nlModle = [YZLNewsListModel yzlNewsListModelWithDic:dic];
            [self.newsArray addObject:nlModle];
        }
        hpModel.newsList = self.newsArray;
        
        [self.modelArray addObject:hpModel];
        
        // 关闭上下拉刷新
        [_tableView headerEndRefreshing];
        [_tableView footerEndRefreshing];
        
        [_tableView reloadData];
        
    } fail:^(NSError *error) {
        NSLog(@"No---->");
    }];
    
}

#pragma mark - 下拉刷新
- (void)addHeader {
    // self赋值
    __block YZLHomePageCell *hpCell = self;
    
    // 创建下拉
    [_tableView addHeaderWithCallback:^{
        hpCell.nextInteger = 0;
        hpCell.isUpLoading = NO;
        [hpCell handleDataWithList:hpCell.nextInteger];
    }];
    // 开机自启
    [_tableView headerBeginRefreshing];
}

#pragma mark - 上拉加载
- (void)addFooter {
    __block YZLHomePageCell *hpCell = self;
    
    // 创建上拉
    [_tableView addFooterWithCallback:^{
        hpCell.nextInteger += 10;
        hpCell.isUpLoading = YES;
        [hpCell handleDataWithList:hpCell.nextInteger];
    }];
}

#pragma mark - 重写初始化
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // 配置 tabelView
        self.tableView = [[UITableView alloc] init];
        [self.contentView addSubview:self.tableView];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        // 重定池
        [self.tableView registerClass:[YZLNewsListCell class] forCellReuseIdentifier:@"newsReuse"];
        [self.tableView registerClass:[YZLNewsScrollCell class] forCellReuseIdentifier:@"scrollReuse"];
        
    }
    return self;
}

#pragma mark - 布局
- (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {
    // 让 tableView 和 collectionView 一样大
    self.tableView.frame = self.contentView.frame;
    // 数组初始化，使得数组在上拉加载是不会清空
    self.modelArray = [NSMutableArray array];
    self.newsArray = [NSMutableArray array];
}

#pragma mark - 重写 set 方法
- (void)setUrlDic:(NSDictionary *)urlDic {
    if (_urlDic != urlDic) {
        _urlDic = urlDic;
    }
    

    // 调用上下拉，默认开机下拉
    self.isUpLoading = NO;
    [self addHeader];
    [self addFooter];

    
}

#pragma mark -  row每行的高
- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    YZLHomePageModel *hgModel = [self.modelArray lastObject];
    // 判断是否为第一个 Item
    if (!self.isZero) {
        return hgModel.newsList.count + 1;
    } else
        return hgModel.newsList.count;

}

#pragma mark - 自定义 cell 赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    YZLHomePageModel *hpModel = [self.modelArray lastObject];
   
    YZLFocusListModel *flModel = [hpModel.focusList objectForKey:@"focusList"];
    // 新闻 cell
    YZLNewsListCell *nCell = [tableView dequeueReusableCellWithIdentifier:@"newsReuse"];
    // 判断是否为第一个 Item
    if (!self.isZero) {
        // 是，则将第一个 cell设置为轮播图
        if (indexPath.row == 0) {
            YZLNewsScrollCell *sCell = [tableView dequeueReusableCellWithIdentifier:@"scrollReuse"];
            sCell.model = flModel;
            sCell.delegate = self;
            return sCell;
        } else {
            // 其他 cell 填充新闻
    
            YZLNewsListModel *newsModel = [self.newsArray objectAtIndex:indexPath.row - 1];
            nCell.model = newsModel;
            return nCell;
        }
    } else {
        // 否则，全部填充新闻
        YZLNewsListModel *newsModel = [self.newsArray objectAtIndex:indexPath.row];
        nCell.model = newsModel;
        return nCell;
    }
    
}

#pragma mark - 自适应 cell 的高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 判断是否为轮播图
    if (!self.isZero && indexPath.row == 0) {

        return kWidth / 2;
       
    } else return (kHeight - 160) / 5.5;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!self.isZero && indexPath.row != 0) {
        YZLNewsListModel *model = [self.newsArray objectAtIndex:indexPath.row - 1];
        [self.delegate pushNewsListDetailsWithString:model.newsLink withType:model.newsType];
    } else {
        YZLNewsListModel *model = [self.newsArray objectAtIndex:indexPath.row];
        [self.delegate pushNewsListDetailsWithString:model.newsLink withType:model.newsType];
    }
}

- (void)pushNewsScrollWithNumber:(NSInteger)number {
    YZLHomePageModel *hpModel = [self.modelArray lastObject];
    YZLFocusListModel *flModel = [hpModel.focusList objectForKey:@"focusList"];
    YZLFocusImgs *fiModel = [flModel.focusImgs objectAtIndex:number / kWidth - 1];
    if ([fiModel.type integerValue] == 1 || [fiModel.type integerValue] == 3) {
        [self.delegate pushNewsListDetailsWithString:fiModel.newsLink withType:@"2"];
    } else if ([fiModel.type integerValue] == 4) {
        [self.delegate pushNewsListDetailsWithString:fiModel.newsLink withType:@"1"];
    }
}

@end
